/*
 * Copyright 2010 JAPIS
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.xdoclet.ignore;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.List;


/**
 * Constructs a context with mocked objects for plugin tests.
 * 
 * @author japis.3des
 */
public class PluginContext {

    /**
     * Factory containing uknown tags.
     */
    private MockDocletTagFactory factory;

    /**
     * Output messages that would go to <code>System.out</code>.
     */
    private ByteArrayOutputStream output;

    /**
     * See {@link #getPlugin()}.
     */
    private IgnorePlugin plugin;

    /**
     * Constructs new mock context with a plugin instance.
     */
    public PluginContext() {
        super();
        MockMetadataProvider provider = new MockMetadataProvider();
        this.factory = (MockDocletTagFactory) provider.getDocletTagFactory();
        this.output = new ByteArrayOutputStream();
        this.plugin = new IgnorePlugin(null, provider, null);
        this.plugin.setOutput(new PrintStream(this.output));
    }

    /**
     * Plugin instance that uses mock objects.
     * 
     * @return the plugin instance to test
     */
    public IgnorePlugin getPlugin() {
        return this.plugin;
    }

    /**
     * Adds an uknown tag to the unknown tag list. Only
     * {@link com.thoughtworks.qdox.model.DocletTag} instances should be in the
     * list, but since it is not protected, we must
     * expect other objects as well.
     * 
     * @param obj a tag or invalid object
     */
    public void addUnknownTag(Object obj) {
        List list = this.factory.getUnknownTags();
        list.add(obj);
    }

    /**
     * Return the plugin output as text.
     * 
     * @return plugin output text
     */
    public String getOutput() {
        String string;
        try {
            this.output.flush();
        } catch (IOException e) {
            throw new IllegalStateException("Error flushing output.");
        }
        try {
            string = this.output.toString("UTF-8");
        } catch (UnsupportedEncodingException e) {
            // never happens, since UTF-8 is supported
            throw new IllegalStateException("UTF-8 unsupported.");
        }
        return string;
    }

}
